package com.hmall.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.common.exception.UnauthorizedException;
import com.hmall.common.utils.CollUtils;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final JwtTool jwtTool;    // token工具
    private final AuthProperties authProperties;   // 路径列表
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();  // hutool包中提供的路径匹配工具

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求头
        ServerHttpRequest request = exchange.getRequest();
        // 获取请求路径，判断是否需要拦截
        if(isExclude(request.getPath().toString()))
            return chain.filter(exchange);
        // 获取token
        String token = null;
        List<String> authorizationHeaders = request.getHeaders().get("authorization");
        if(!CollUtils.isEmpty(authorizationHeaders))
            token = authorizationHeaders.get(0);

        // 校验并解析token
        Long userId = null;
        try {
            // 解析成功，拿到用户id
            userId = jwtTool.parseToken(token);
        } catch (UnauthorizedException e) {
            // 解析失败，返回401未授权错误
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }

        // 传递用户信息
        String userInfo = userId.toString();
        ServerWebExchange ex = exchange.mutate().request(builder -> builder.header("user-info", userInfo)).build();
        // 放行
        return chain.filter(ex);
    }

    // 判断当前请求路径是否在排除列表中
    private boolean isExclude(String path) {
        return authProperties.getExcludePaths().stream().anyMatch(s -> antPathMatcher.match(s, path));
    }

    @Override
    public int getOrder() {
        return 0;  // 过滤器执行顺序，越小越先执行，比网关过滤器链的最后一个过滤器NettyRoutingFilter先执行就ok
    }
}

